﻿using K8.CBB;
using K8.EF;
using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRBW.Spi;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class WcsTaskImpl : ITaskService
{
    IWcsTaskRepository _wcsTaskRepository = new WcsTaskRepository();
    ITaskCmdRepositories _taskCmdRepositories = new BTaskCmdRepositories();
    IMesProductRepositories _mesProductRepositories = new MesProductRepositories();
    IRcsEquipRepositories _rcsEquipRepositories = new RcsEquipRepositories();
    IRcsLocationRepositories _rcsLocationRepositories = new RcsLocationRepositories();
    IMesOutOrdersRepositories _mesOutOrdersRepositories = new MesOutOrdersRepositories();
    IWcsEquipLocHoldRepositories _wcsEquipLocHoldRepositories = new WcsEquipLocHoldRepositories();


    public TaskAndCmdBean QueryFrist(Expression<Func<POWcsTask, bool>> whereExpression)
    {
        Expression<Func<POWcsTaskCmd, bool>> whereCmdExpression = x => true;
        var task = _wcsTaskRepository.First(whereExpression);
        if (task is null) return null;

        whereCmdExpression = whereCmdExpression.And(d => d.TaskId == task.Id);
        var cmd = _taskCmdRepositories.First(whereCmdExpression);
        if (cmd is null) return null;

        return new TaskAndCmdBean()
        {
            Task = task,
            Cmd = cmd
        };
    }

    public TaskAndCmdBean QueryByTaskNo(int taskNo)
    {
        Expression<Func<POWcsTaskCmd, bool>> whereCmdExpression = x => true;
        Expression<Func<POWcsTask, bool>> whereTaskExpression = x => true;

        whereTaskExpression = whereTaskExpression.And(d => d.TaskNo == taskNo);
        var task = _wcsTaskRepository.First(whereTaskExpression);
        if (task is null) return null;

        whereCmdExpression = whereCmdExpression.And(d => d.TaskId == task.Id);
        var cmd = _taskCmdRepositories.First(whereCmdExpression);
        if (cmd is null) return null;

        return new TaskAndCmdBean()
        {
            Task = task,
            Cmd = cmd
        };
    }

    public TaskAndCmdBean GetTaskByTaskId(int taskNo)
    {
        Expression<Func<POWcsTaskCmd, bool>> whereExpression = x => true;
        Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;

        whereWcsTaskExpression = whereWcsTaskExpression.And(f => f.TaskNo == taskNo && f.TaskStatus != (int)EnumTaskStatus.Finish && f.UseFlag == 1);
        var task = _wcsTaskRepository.First(whereWcsTaskExpression);
        whereExpression = whereExpression.And(f => f.TaskNo == taskNo && f.CmdStatus != (int)EnumTaskStatus.Finish && f.UseFlag == 1);
        var cmd = _taskCmdRepositories.First(whereExpression);
        if (cmd is null) return null;

        return new TaskAndCmdBean
        {
            Task = task,
            Cmd = cmd,
        };
    }

    public MesProductTask CreateSlibeTableTask(string equip_name, int source_type)
    {
        Expression<Func<MesProduct, bool>> whereMesProductExpression = x => true;
        Expression<Func<PORcsEquip, bool>> wherePORcsEquipExpression = x => true;
        Expression<Func<PORcsLocation, bool>> whereRcsLocationExpression = x => true;
        Expression<Func<POWcsTaskCmd, bool>> whereWcsTaskCmdExpression = x => true;
        MesProductTask mesProductTasks = new MesProductTask();

        //判断是否存在该滑台任务
        if (source_type == 2)
        {
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.AbnormalSlide && f.UseFlag == 1);
            whereMesProductExpression = whereMesProductExpression.And(f => f.SourceType == source_type.ToString() && f.Status == (int)EnumExecStatus.Add && f.ExpriationTime > DateTime.Now);
        }
        else
        {
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.StorageSlide && f.UseFlag == 1);
            whereMesProductExpression = whereMesProductExpression.And(f => f.EquipName == equip_name && f.SourceType == source_type.ToString() && f.Status == (int)EnumExecStatus.Add && f.ExpriationTime > DateTime.Now);
        }

        //开始位
        PORcsLocation startRcsLocation = _rcsLocationRepositories.First(whereRcsLocationExpression);
        if (startRcsLocation == null)
        {
            WriteLog("滑台不存在");
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -4;
            return mesProductTasks;
        }

        whereWcsTaskCmdExpression = whereWcsTaskCmdExpression.And(f => (f.CmdStatus == (int)EnumTaskStatus.Executed || f.CmdStatus == (int)EnumTaskStatus.Executable) && f.StartLoc == startRcsLocation.Id);
        POWcsTaskCmd wcsTaskCmd = _taskCmdRepositories.First(whereWcsTaskCmdExpression);
        if (wcsTaskCmd != null)
        {
            WriteLog("已存在该滑台任务");
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -6;
            return mesProductTasks;
        }
        //1、获取所有产出订单

        MesProduct mesProduct = _mesProductRepositories.First(whereMesProductExpression);
        if (mesProduct == null)
        {
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -1;
            return mesProductTasks;
        }
        //2、判断设备是否正常
        //滑台设备是否可用
        wherePORcsEquipExpression = wherePORcsEquipExpression.And(f => f.EquipCode == equip_name && f.UseFlag == 1);
        var rcsEquip = _rcsEquipRepositories.First(wherePORcsEquipExpression);
        if (rcsEquip == null)
        {
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -2;
            return mesProductTasks;
        }
        if (rcsEquip.EquipEnable == 0)
        {
            WriteLog("创建滑台任务》滑台设备不可用");
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -3;
            return mesProductTasks;
        }


        TaskDTO dto = new TaskDTO()
        {
            StartLoc = startRcsLocation.Id.GetValueOrDefault(),//开始位置
            TargetLoc = startRcsLocation.Id.GetValueOrDefault(),//目标位置
            Type = (int)EnumTaskType.SlibeTable,
            StartEquip = rcsEquip.Id,//开始设备
            MesProductId = mesProduct.Id,
            OrderId = mesProduct.Id,
            Mark = source_type == 2 ? 3 : 4,
            material_id = mesProduct.PartNumber,
            Innerdiameter = mesProduct.innerdiameter.GetValueOrDefault()
        };
        var task = _wcsTaskRepository.CreateTaskAndCmd(dto);
        if (task != null && task.POWcsTask is not null && task.POWcsTaskCmd is not null)
        {
            //执行事务
            int result = _wcsTaskRepository.ExecAddTran(task.POWcsTask, task.POWcsTaskCmd);
            if (result > 0)
            {
                MesProductTask mesProductTask = new MesProductTask();
                mesProductTask.Innerdiameter = float.Parse(mesProduct.innerdiameter.GetValueOrDefault().ToString());
                mesProductTask.TaskNo = task.POWcsTask.TaskNo.GetValueOrDefault();
                return mesProductTask;
            }
            mesProductTasks.Innerdiameter = 0;
            mesProductTasks.TaskNo = -5;
            return mesProductTasks;
        }
        mesProductTasks.Innerdiameter = 0;
        mesProductTasks.TaskNo = 0;
        return mesProductTasks;
    }

    public int CreateWarehouseing(long equip_id, int status,string slidtable)
    {
        Expression<Func<MesProduct, bool>> whereMesProductExpression = x => true;
        Expression<Func<PORcsEquip, bool>> wherePORcsEquipExpression = x => true;
        Expression<Func<PORcsLocation, bool>> whereRcsLocationExpression = x => true;
        Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;

        //1、获取所有产出订单
        if (string.IsNullOrEmpty(slidtable))
        {
            whereMesProductExpression = whereMesProductExpression.And(f => f.Status == status && f.SourceType =="2" && f.ExpriationTime > DateTime.Now);
        }
        else
        {
            whereMesProductExpression = whereMesProductExpression.And(f => f.Status == status && f.SourceType == "1" && f.EquipName == slidtable && f.ExpriationTime > DateTime.Now);
        }
            
        MesProduct mesProduct = _mesProductRepositories.First(whereMesProductExpression);
        if (mesProduct == null) return -1;

        //判断是否创建了龙门任务
        whereWcsTaskExpression = whereWcsTaskExpression.And(f => f.TaskType == 1&& f.StartEquip== equip_id && f.MesId== mesProduct.Id);
        POWcsTask wcsTask = _wcsTaskRepository.First(whereWcsTaskExpression);
        if (wcsTask != null)
        {
            WriteLog("已存在该任务");
            return -6;
        }


        //2、判断设备是否正常
        //设备是否可用
        wherePORcsEquipExpression = wherePORcsEquipExpression.And(f => f.Id == equip_id && f.UseFlag == 1);
        var rcsEquip = _rcsEquipRepositories.First(wherePORcsEquipExpression);
        if (rcsEquip == null) return -2;
        if (rcsEquip.EquipEnable == 0)
        {
            WriteLog("创建龙门入库》龙门设备不可用");
            return -3;
        }

        if (mesProduct.SourceType == "2")
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.AbnormalSlide && f.UseFlag == 1);
        else
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.StorageSlide && f.LocCode == mesProduct.EquipName && f.UseFlag == 1);

        //开始位
        PORcsLocation startRcsLocation = _rcsLocationRepositories.First(whereRcsLocationExpression);
        if (startRcsLocation == null) return -4;
        //结束位
        POWcsEquipLocHold wcsEquipLocHold = _rcsLocationRepositories.GetDistancePoint(mesProduct, startRcsLocation);
        if (wcsEquipLocHold is null)
        {
            WriteLog($"创建龙门入库任务》未查询到目标库位:{mesProduct.ToJson()}", true);
            return -5;
        }

        TaskDTO dto = new TaskDTO()
        {
            StartLoc = startRcsLocation.Id.GetValueOrDefault(),//开始位置
            TargetLoc = wcsEquipLocHold.LocId.GetValueOrDefault(),//目标位置
            Type = (int)EnumTaskType.Warehousing,
            StartEquip = wcsEquipLocHold.EquipId,//开始设备
            MesProductId = mesProduct.Id,
            //OrderId = mesProduct.Id,
            Innerdiameter= mesProduct.innerdiameter.GetValueOrDefault(),
            Mark = mesProduct.SourceType == "2" ? 3 : 4,
            material_id = mesProduct.PartNumber,

        };
        var task = _wcsTaskRepository.CreateTaskAndCmd(dto);
        if (task != null && task.POWcsTask is not null && task.POWcsTaskCmd is not null)
        {
            //执行事务
            int result = _wcsTaskRepository.ExecAddWarehouseingTaskTran(task.POWcsTask, task.POWcsTaskCmd);
            if (result > 0)
            {
                return task.POWcsTask.TaskNo.GetValueOrDefault();
            }
            return -1;
        }
        return 0;
    }

    public int CreateExWarehouse(long equip_id, int status)
    {
        Expression<Func<MesOutOrder, bool>> whereMesOutOrderExpression = x => true;
        Expression<Func<MesOutOrder, bool>> whereCancelOrderExpression = x => true;
        Expression<Func<PORcsEquip, bool>> wherePORcsEquipExpression = x => true;
        Expression<Func<PORcsEquip, bool>> whereRcsEquipExpression = x => true;
        Expression<Func<PORcsLocation, bool>> whereRcsLocationExpression = x => true;
        Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;

        //验证订单是否已经执行
        //1、获取所有订单
        //1、获取所有产出订单
        whereMesOutOrderExpression = whereMesOutOrderExpression.And(f => f.Status == status && f.StopFlag == "N" && f.UpdateFlag == 1);
        var mesOutOrder = _mesOutOrdersRepositories.First(whereMesOutOrderExpression);
        if (mesOutOrder == null) return -1;
        //判断是否创建了龙门任务
        if (mesOutOrder.OrderType==2)
        {
            whereWcsTaskExpression = whereWcsTaskExpression.And(f => f.TaskType == 2 && f.StartEquip == equip_id && f.OrderId == mesOutOrder.Id);
        }
        else
        {
            whereWcsTaskExpression = whereWcsTaskExpression.And(f => f.TaskType == 2 && f.StartEquip == equip_id && f.OrderId == mesOutOrder.Id);
        }

        POWcsTask wcsTask = _wcsTaskRepository.First(whereWcsTaskExpression);
        if (wcsTask != null)
        {
            WriteLog($"龙门出库任务》已存在该龙门任务，出库任务号：{mesOutOrder.Id}");
            return -6;
        }

        //2、判断设备是否正常
        //龙门设备是否可用
        wherePORcsEquipExpression = wherePORcsEquipExpression.And(f => f.Id == equip_id && f.UseFlag == 1);
        var rcsEquip = _rcsEquipRepositories.First(wherePORcsEquipExpression);
        if (rcsEquip == null) return -2;
        if (rcsEquip.EquipEnable == 0)
        {
            WriteLog("龙门出库任务》龙门设备不可用");
            return -3;
        }
        //开始位
        PORcsLocation startRcsLocation = null;
        if (mesOutOrder.OrderType == 2)
        {
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.Id == mesOutOrder.StartLoc && f.UseFlag == 1 && f.LocSize == mesOutOrder.Innerdiameter);
            whereRcsEquipExpression = whereRcsEquipExpression.And(f => f.EquipType == 14 && f.UseFlag == 1);
            startRcsLocation = _rcsLocationRepositories.QueryLocation(whereRcsLocationExpression);
        }
        else
        {
            whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.Location && f.MaterialId == mesOutOrder.PartNumber && f.OutEnable == 1 && f.OutLock == 1 && f.UseFlag == 1 && f.LocSize == mesOutOrder.Innerdiameter);
            whereRcsEquipExpression = whereRcsEquipExpression.And(f => f.EquipType == 7 && f.UseFlag == 1);
            var (loc, result) = _rcsLocationRepositories.QueryStartLocation(whereRcsLocationExpression);
            if (result == -1)
            {
                WriteLog($"创建龙门出库任务》未查询到质检过的物料信息或者库位物料被锁定，请检查库内信息,任务取消，订单号:{mesOutOrder.Id}", true);
                //没有查询到物料，任务取消
                mesOutOrder.Remarks = "未查询到质检过的物料信息,任务取消";
                mesOutOrder.StopFlag = "Y";
                mesOutOrder.ErrorFlag = "1";
                whereCancelOrderExpression = whereCancelOrderExpression.And(f => f.Id == mesOutOrder.Id);
                _mesOutOrdersRepositories.Update(whereCancelOrderExpression, mesOutOrder);
                return -11;
            }
            if (result == -2)
            {
                WriteLog($"创建龙门出库任务》未查询到物料信息,任务取消，订单号:{mesOutOrder.Id}", true);
                //没有查询到物料，任务取消
                mesOutOrder.Remarks = "未查询到物料信息,任务取消";
                mesOutOrder.StopFlag = "Y";
                mesOutOrder.ErrorFlag = "1";
                whereCancelOrderExpression = whereCancelOrderExpression.And(f => f.Id == mesOutOrder.Id);
                _mesOutOrdersRepositories.Update(whereCancelOrderExpression, mesOutOrder);
                return -11;
            }
            startRcsLocation = loc;
        }
        if (startRcsLocation == null)
        {
            WriteLog($"创建龙门出库任务》未查询到库内物料或者未查询到可出库物料,任务取消，订单号:{mesOutOrder.Id}", true);
            //没有查询到物料，任务取消
            mesOutOrder.Remarks = "未查询到物料信息,任务取消";
            mesOutOrder.StopFlag = "Y";
            mesOutOrder.ErrorFlag = "1";
            whereCancelOrderExpression = whereCancelOrderExpression.And(f => f.Id== mesOutOrder.Id);
            var result = _mesOutOrdersRepositories.Update(whereCancelOrderExpression, mesOutOrder);
            return -4;
        }
        //结束位
        PORcsEquip wcsEquip = null;
        if (mesOutOrder.OrderType == 2)
        {
            wcsEquip = _rcsEquipRepositories.First(whereRcsEquipExpression);
        }
        else
        {
            wcsEquip = _rcsEquipRepositories.QueryOutSildeTable(whereRcsEquipExpression, mesOutOrder.TargetEquip);
        }
          
        if (wcsEquip is null)
        {
            WriteLog($"创建龙门出库任务》未查询到目标库位:{mesOutOrder.Id}", true);
            return -5;
        }

        TaskDTO dto = new TaskDTO()
        {
            StartLoc = startRcsLocation.Id.GetValueOrDefault(),//开始位置
            TargetLoc = wcsEquip.Id.GetValueOrDefault(),//目标位置
            Type = (int)EnumTaskType.Exwarehouse,
            StartEquip = rcsEquip.Id,//开始设备
            OrderId = mesOutOrder.Id,
            MesProductId = startRcsLocation.Pid,
            Mark = mesOutOrder.OrderType == 2?2:0,
            material_id = mesOutOrder.PartNumber,
            Innerdiameter= mesOutOrder.Innerdiameter.GetValueOrDefault()
        };
        var task = _wcsTaskRepository.CreateTaskAndCmd(dto);
        if (task != null && task.POWcsTask is not null && task.POWcsTaskCmd is not null)
        {
            //执行事务
            int result = _wcsTaskRepository.ExecAddTran(task.POWcsTask, task.POWcsTaskCmd);
            if (result > 0)
            {
                return task.POWcsTask.TaskNo.GetValueOrDefault();
            }
            return -1;
        }
        return 0;
    }

    public int CreateTruss(long equip_id,string targetName, int status)
    {
        Expression<Func<MesOutOrder, bool>> whereMesOutOrderExpression = x => true;
        Expression<Func<PORcsEquip, bool>> wherePORcsEquipExpression = x => true;
        Expression<Func<PORcsEquip, bool>> whereRcsEquipExpression = x => true;
        Expression<Func<PORcsLocation, bool>> whereRcsLocationExpression = x => true;
        Expression<Func<PORcsLocation, bool>> whereCallRcsLocationExpression = x => true;
        Expression<Func<POWcsEquipLocHold, bool>> whereEquipLocHoldExpression = x => true;
        Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;

        //1、获取所有产出订单
        var mesOutOrder = _mesOutOrdersRepositories.GetMesOutOrderCompleteByStatus(targetName,status);
        if (mesOutOrder == null)
        {
            WriteLog($"创建桁架任务》{equip_id}未找到叫料订单");
            return -3;
        }
        //判断任务是否已经创建
        whereWcsTaskExpression = whereWcsTaskExpression.And(f => f.TaskType == 3 && f.StartEquip == equip_id && f.OrderId == mesOutOrder.Id);
        POWcsTask wcsTask = _wcsTaskRepository.First(whereWcsTaskExpression);
        if (wcsTask != null)
        {
            WriteLog($"创建桁架任务》{equip_id}已存在任务");
            return -6;
        }
        //判断设备是否正常,桁架设备是否可用
        wherePORcsEquipExpression = wherePORcsEquipExpression.And(f => f.Id == equip_id && f.UseFlag == 1);
        var rcsEquip = _rcsEquipRepositories.First(wherePORcsEquipExpression);
        if (rcsEquip == null) return -2;
        if (rcsEquip.EquipEnable == 0)
        {
            WriteLog($"创建桁架任务》{equip_id}桁架设备不可用");
            return -9;
        }
        //开始位 出库滑台
        whereEquipLocHoldExpression = whereEquipLocHoldExpression.And(f => f.EquipId == rcsEquip.Id && f.UseFlag == 1);
        POWcsEquipLocHold wcsEquipLocHold = _wcsEquipLocHoldRepositories.First(whereEquipLocHoldExpression);
        if (wcsEquipLocHold == null)
        {
            WriteLog($"创建桁架任务》未查询匹配出库滑台:_wcsEquipLocHold：{mesOutOrder.Id}", true);
            return -5;
        }
        whereRcsLocationExpression = whereRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.OutboundSlide && f.Id == wcsEquipLocHold.LocId && f.OutEnable == 1 && f.UseFlag == 1);
        PORcsLocation startRcsLocation = _rcsLocationRepositories.First(whereRcsLocationExpression);
        if (startRcsLocation == null)
        {
            WriteLog($"创建桁架任务》未查询匹配出库滑台或者滑台目前不可用:startRcsLocation：{wcsEquipLocHold.LocId}", true);
            return -6;
        }
        //结束位 机台
        whereRcsEquipExpression = whereRcsEquipExpression.And(f => f.EquipCode == mesOutOrder.TargetEquip);
        PORcsEquip wcsEquip = _rcsEquipRepositories.First(whereRcsEquipExpression);
        if (wcsEquip is null)
        {
            WriteLog($"创建桁架任务》未查询到目标机台请检查设备表配置:{mesOutOrder.Id}", true);
            return -7;
        }
        whereCallRcsLocationExpression = whereCallRcsLocationExpression.And(f => f.LocType == (int)EnumLocType.CallingMachine && f.LocCode == mesOutOrder.TargetEquip && f.OutEnable == 1 && f.UseFlag == 1);
        PORcsLocation endRcsLocation = _rcsLocationRepositories.First(whereCallRcsLocationExpression);
        if (endRcsLocation == null)
        {
            WriteLog($"创建桁架任务》叫料机台不可用:endRcsLocation：{mesOutOrder.TargetEquip}", true);
            return -8;
        }
        TaskDTO dto = new TaskDTO()
        {
            StartLoc = startRcsLocation.Id.GetValueOrDefault(),//开始位置
            TargetLoc = endRcsLocation.Id.GetValueOrDefault(),//目标位置
            Type = (int)EnumTaskType.Truss,
            StartEquip = rcsEquip.Id,//开始设备
            MesProductId = mesOutOrder.Id,
            OrderId = mesOutOrder.Id,
            Mark = 0,
            material_id = mesOutOrder.PartNumber,
            Innerdiameter= mesOutOrder.Innerdiameter.GetValueOrDefault()
        };
        var task = _wcsTaskRepository.CreateTaskAndCmd(dto);
        if (task != null && task.POWcsTask is not null && task.POWcsTaskCmd is not null)
        {
            //执行事务
            int result = _wcsTaskRepository.ExecAddTran(task.POWcsTask, task.POWcsTaskCmd);
            if (result > 0)
            {
                return task.POWcsTask.TaskNo.GetValueOrDefault();
            }
            return -1;
        }
        return 0;
    }

    public int UpdateTaskStatus(int taskNo, int status, long locId = 0)
    {
        var task = GetTaskByTaskId(taskNo);
        if (task.Task is null || task.Cmd is null) return 0;


        task.Task.TaskStatus = status;
        task.Task.UpdateTime = DateTime.Now;

        task.Cmd.CmdStatus = status;
        task.Cmd.UpdateTime = DateTime.Now;
 

        long? finishLoc = null;
        int? finishMode = (int)EnumTaskStatus.Create;
        DateTime? finishTime = null;
        //加上了入库前验证  lsq
        if (status == (int)EnumTaskStatus.Finish)
        {
            // 完成时修改
            finishLoc = locId;
            finishMode = (int)EnumFinishMode.NormalEnd;
            finishTime = DateTime.Now;

            task.Task.TaskStatus = status;
            task.Task.FinishLoc = finishLoc;
            task.Task.FinishMode = finishMode;
            task.Task.FinishTime = finishTime;


            task.Cmd.CmdStatus = status;
            task.Cmd.FinishLoc = finishLoc;
            task.Cmd.FinishMode = finishMode;
            task.Cmd.FinishTime = finishTime;
           
        }
        return _wcsTaskRepository.ExecUpdateByTaskStatusTran(task.Task, task.Cmd,  status); 
    }

    public int UpdateTaskAndCmdStatus(long locId, int taskNo, int status)
       => status switch
       {
           (int)EnumTaskStatus.Executable => UpdateTaskStatus(taskNo, (int)EnumTaskStatus.Executable, locId),
           (int)EnumTaskStatus.Executed => UpdateTaskStatus(taskNo, (int)EnumTaskStatus.Executed, locId),
           (int)EnumTaskStatus.Finish => UpdateTaskStatus(taskNo, (int)EnumTaskStatus.Finish, locId),
           _ => 0,
       };

    public List<TaskCmdAndLocDto> GetTaskAndCmdBeanByCmdEquipId(long equipId)
    {
        return _wcsTaskRepository.GetTaskAndCmdBeanByCmdEquipId(equipId);
    }

    public List<TaskCmdAndLocDto> GetTrussTaskAndCmdBeanByCmdEquipId(long equipId)
    {
        return _wcsTaskRepository.GetTrussTaskAndCmdBeanByCmdEquipId(equipId);
    }

    public int ClearManualCleanTask()
    {
        try
        {
            Expression<Func<MesProduct, bool>> whereMesProductExpression = x => true;
            whereMesProductExpression = whereMesProductExpression.And(d => d.Status == (int)EnumExecStatus.ManualClean);
            var _mesProduct = _mesProductRepositories.Query(whereMesProductExpression);

            Expression<Func<MesOutOrder, bool>> whereMesOutOrderExpression = x => true;
            whereMesOutOrderExpression = whereMesOutOrderExpression.And(d => d.Status == (int)EnumExecStatus.ManualClean);

            var _mesOutOrders = _mesOutOrdersRepositories.Query(whereMesOutOrderExpression);

            //删除产出
            if (_mesProduct != null && _mesProduct.Count() > 0)
            {
                _mesProductRepositories.Deletes(_mesProduct);
            }


            //删除叫料订单
            if (_mesOutOrders != null && _mesOutOrders.Count() > 0)
            {
                _mesOutOrdersRepositories.Deletes(_mesOutOrders);
            }

            //人工清理
            Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;
            whereWcsTaskExpression=whereWcsTaskExpression.And(d => d.TaskWmsStatus == (int)EnumExecStatus.ManualClean);

            var result = _wcsTaskRepository.Query(whereWcsTaskExpression);
            if (result != null || result.Count() > 0)
            {
                var _taskCmds = _taskCmdRepositories.Query();
                foreach (var item in result)
                {
                    var cmd = _taskCmds.SingleOrDefault(d => d.TaskId == item.Id);
                    if (cmd != null)
                    {

                        _wcsTaskRepository.ExecDelTran(item, cmd);
                    }
                    else
                    {

                        _wcsTaskRepository.DeleteById(item.Id);
                    }
                    if (item.TaskType == (int)EnumTaskType.Warehousing)
                    {
                        if (_mesProduct == null || _mesProduct.Count() == 0) continue;
                        var ids = _mesProduct.Where(d => d.Id == item.MesId);

                        _mesProductRepositories.Deletes(ids);
                    }
                    if (item.TaskType == (int)EnumTaskType.Exwarehouse)
                    {
                        if (_mesOutOrders == null || _mesOutOrders.Count() == 0) continue;
                        var ids = _mesOutOrders.Where(d => d.Id == item.OrderId);

                        _mesOutOrdersRepositories.Deletes(ids);
                    }
                }
            }

            //人工完成
            Expression<Func<POWcsTask, bool>> whereWcsTaskCompletedExpression = x => true;
            whereWcsTaskCompletedExpression=whereWcsTaskCompletedExpression.And(d => d.TaskWmsStatus == (int)EnumExecStatus.CompletedManually);
            var _taskCmd = _taskCmdRepositories.Query();
            var _wcsTask = _wcsTaskRepository.First(whereWcsTaskCompletedExpression);
            if (_wcsTask != null)
            {
                if (_wcsTask.TaskType == (int)EnumTaskType.Warehousing)
                {
                    int status = SwitchMesProductMethod(_wcsTask.TaskType.GetValueOrDefault());
                    var cmd = _taskCmd.SingleOrDefault(d => d.TaskId == _wcsTask.Id);
                    if (cmd != null)
                    {

                        var mesProduct = new MesProduct()
                        {
                            Id = _wcsTask.MesId,
                            Status = status,
                        };
                        var bean = new POWcsTask
                        {
                            Id = _wcsTask.Id,
                            TaskStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };

                        var cmdBean = new POWcsTaskCmd
                        {
                            Id = _wcsTask.Id,
                            TaskId = cmd.Id,
                            CmdStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };
                        _mesProductRepositories.Update(mesProduct);
                        _wcsTaskRepository.ExecUpdateTran(_wcsTask, cmd);

                    }
                    else
                    {
                        var mesProduct = new MesProduct()
                        {
                            Id = _wcsTask.MesId,
                            Status = status,
                        };
                        var bean = new POWcsTask
                        {
                            Id = _wcsTask.Id,
                            TaskStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };
                        _mesProductRepositories.Update(mesProduct);
                        _wcsTaskRepository.Update(bean);
                    }

                }
                if (_wcsTask.TaskType == (int)EnumTaskType.Exwarehouse)
                {
                    int status = SwitchMesOrderMethod(_wcsTask.TaskType.GetValueOrDefault());
                    var cmd = _taskCmd.SingleOrDefault(d => d.TaskId == _wcsTask.Id);
                    if (cmd != null)
                    {
                        var mesOrder = new MesOutOrder()
                        {
                            Id = _wcsTask.MesId,
                            Status = status,
                        };
                        var bean = new POWcsTask
                        {
                            Id = _wcsTask.Id,
                            TaskStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };

                        var cmdBean = new POWcsTaskCmd
                        {
                            Id = _wcsTask.Id,
                            TaskId = cmd.Id,
                            CmdStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };
                        _mesOutOrdersRepositories.Update(mesOrder);
                        _wcsTaskRepository.ExecUpdateTran(_wcsTask, cmd);

                    }
                    else
                    {
                        var mesOrder = new MesOutOrder()
                        {
                            Id = _wcsTask.MesId,
                            Status = status,
                        };
                        var bean = new POWcsTask
                        {
                            Id = _wcsTask.Id,
                            TaskStatus = 9,
                            FinishLoc = _wcsTask.TargetLoc,
                            FinishMode = 1,
                            FinishTime = DateTime.Now,
                        };
                        _mesOutOrdersRepositories.Update(mesOrder);
                        _wcsTaskRepository.Update(bean);
                    }

                    MesOutOrder mesOutOrder = new MesOutOrder();
                    //出库
                    if (_wcsTask.Mark == 0)
                    {
                        mesOutOrder.Id = _wcsTask.OrderId.ToString();
                        mesOutOrder.Status = (int)EnumMesOutOrder.ExWarehouseCompleted;
                        mesOutOrder.TargetLoc = _wcsTask.TargetLoc;
                    }
                    //人工出库
                    if (_wcsTask.Mark == 1 || _wcsTask.Mark == 2)
                    {
                        mesOutOrder.Id = _wcsTask.OrderId.ToString();
                        mesOutOrder.Status = (int)EnumMesOutOrder.AbnormalCompleted;
                        mesOutOrder.TargetLoc = _wcsTask.TargetLoc;
                    }

                    PORcsLocation rcsLocation = new PORcsLocation();
                    rcsLocation.Id = _wcsTask.StartLoc;
                    rcsLocation.TaskId = null;
                    rcsLocation.TaskOccupy = 0;
                    rcsLocation.TaskOccupyTime = null;
                    rcsLocation.LocHasSku = 0;
                    rcsLocation.SkuRealCount = 0;
                    rcsLocation.UpdateTime = DateTime.Now;
                    rcsLocation.LocHasSkuTime = null;
                    rcsLocation.MaterialId = null;
                    rcsLocation.ProductBatch = string.Empty;
                    rcsLocation.MdTime = null;
                    rcsLocation.Remarks = $"清空货位数据 TaskNO{_wcsTask.TaskNo}";
                    rcsLocation.Pid = _wcsTask.MesId;
                    rcsLocation.LocSize = 0;
                    _mesOutOrdersRepositories.ExecUpdateExWarehousStatusTran(mesOutOrder, rcsLocation, _wcsTask);
                }
            }

            return 1;
        }
        catch (Exception)
        {
            return -1;
        }
    }

    public int SwitchMesOrderMethod(int type)
    {
        //  mes_out_order 0：数据新增；1移库执行中; 2移库完成; 3出库执行中; 4出库完成; 5桁架执行中; 6桁架任务完成; 7 - 人工出库执行中；8人工出库完成,12 - 人工删除,13 - 人工完成 ,15 - wcs清理
        //task任务类型: 1入库任务; 2出库任务; 3桁架任务; 4移库任务；5 - 滑台任务
        int result = 0;
        switch (type)
        {
            case 2:
                result = 4;
                break;
            case 3:
                result = 6;
                break;
            default:
                result = -1;
                break;
        }
        return result;
    }
    public int SwitchMesProductMethod(int type)
    {
        //task任务类型: 1入库任务; 2出库任务; 3桁架任务; 4移库任务；5 - 滑台任务
        //mes_product 0：新增；1：执行中；2：库内；3：出库完成；4:桁架任务完成; 5:滑台任务完成; 11:订单锁定，,12 - 人工删除,13 - 人工完成 ,15 - wcs清理
        int result = 0;
        switch (type)
        {
            case 1:
                result = 2;
                break;
            case 5:
                result = 5;
                break;
            default:
                result = -1;
                break;
        }
        return result;
    }


    public void BakTaskAndOrder()
    {
        Expression<Func<POWcsTask, bool>> whereWcsTaskExpression = x => true;
        whereWcsTaskExpression = whereWcsTaskExpression.And(d => d.TaskStatus == (int)EnumExecStatus.TrussComplete);
        var _wcsTaskList = _wcsTaskRepository.Query(whereWcsTaskExpression);

        var _taskList = _wcsTaskRepository.Query();
        var _cmdList = _taskCmdRepositories.Query();
        var _mesProductList = _mesProductRepositories.Query();
        var _mesOutOrderList = _mesOutOrdersRepositories.Query();

        var db=Db.Default;
        foreach (var item in _wcsTaskList)
        {
            //查询出库订单、查询进库订单、查询滑台任务、查询入库订单
            var _taskOutOrder = _taskList.SingleOrDefault(d => d.OrderId == item.OrderId && d.TaskStatus == (int)EnumExecStatus.ExeWarehouseComplete);
            var _cmdOutOrder = _cmdList.SingleOrDefault(d => d.TaskId == _taskOutOrder.Id);
            
            var _mesOutOrder = _mesOutOrderList.SingleOrDefault(d => d.Id == _taskOutOrder.OrderId);

            var _warehousing = _taskList.SingleOrDefault(d => d.MesId == _taskOutOrder.MesId && d.TaskStatus == (int)EnumExecStatus.InTheWarehouse);
            var _sildeTable = _taskList.SingleOrDefault(d => d.MesId == _taskOutOrder.MesId && d.TaskStatus == (int)EnumExecStatus.SlideComplete);

            var _mesProduct = _mesProductList.SingleOrDefault(d => d.Id == _warehousing.MesId);

            db.BakWcsTasks.CopyFrom(item);
            db.BakWcsTasks.CopyFrom(_taskOutOrder);
            db.BakWcsTasks.CopyFrom(_warehousing);
            db.BakWcsTasks.CopyFrom(_sildeTable);

            db.BakWcsTaskCmds.CopyFrom(_cmdOutOrder);

            db.BakMesOutOrders.CopyFrom(_mesOutOrder);

            db.BakMesProducts.CopyFrom(_mesProduct);
        }
    }
}
